
$(document).ready(function() {
  var _NORMAL = "0000000";
   //Stop from auto commit
  $("form").on("submit",false);
  var VAL = {
  	NORMAL : "0000000"
  };
  var itemInfoCM = [
    {name: 'path_cate' , index: 'path_cate' , label: PATH_CATE_TAG     , width: 60 },
    {name: 'path_id'   , index: 'path_id'   , label: PATH_ID_TAG       , width: 80 },
    {name: 'path_ver'  , index: 'path_ver'  , label: PATH_VER_TAG      , width: 60 }
  ];
  $("#pathListGrd").jqGrid({
      url:"",
      datatype:"local",
      mtype:"POST",
      height:($(window).height() - $("#pathListDiv").offset().top) * 0.95,
      width:$("#pathListDiv").width()*0.99,
      autowidth:false,
      shrinkToFit:false,
      resizable : true,
      loadonce:true,
      viewrecords : true, //显示总记录数
      pager : '#pathListPg',
      rownumbers  :true ,//显示行号
      rowNum:20,         //每页多少行，用于分页
      rownumWidth : 20,  //行号列宽度
      emptyrecords :true ,
      colModel: itemInfoCM,
      gridComplete:function(){
          var gridPager,
              pageLen;
          gridPager = $(this).jqGrid("getGridParam","pager");
          if(gridPager.length<2){
             return false;
          }
          $("#sp_1_"+gridPager.substr(1,pageLen-1) ).hide();
          $(".ui-pg-input").hide();
          $('td[dir="ltr"]').hide(); 
          $(gridPager+"_left").hide();
          $(gridPager+"_center").css({width:0});
      },
      onSelectRow:function(id){
      	var inObj,outObj;
        $("#pathConditionForm  input").attr({"disabled":true});
        $("#pathConditionForm  select").attr({"disabled":true});
        var FIRST_OPE_NO ="FRST";
        var rowData = $(this).jqGrid("getRowData",id);
        var iaryA = {};
        if(rowData.path_id!=""){
          iaryA.path_id    = rowData.path_id;
        }
        if(rowData.path_ver!=""){
          iaryA.path_ver    = rowData.path_ver;
        }
        inObj = {
    	  trx_id     : "XPBISPTH",
          action_flg : "Q",
          iaryA      : [iaryA]
        };
        outObj = comTrxSubSendPostJson(inObj);
        if(outObj.rtn_code === VAL.NORMAL){
        	oaryA = outObj.oaryA;
	        $("#pathIDTxt").val(oaryA.path_id);
	        $("#pathVerTxt").val(oaryA.path_ver);
            $("#pathDscTxt").val(oaryA.path_dsc);
        	SelectDom.setSelect($("#pathCateSel"),oaryA.path_cate);
        	SelectDom.setSelect($("#startBankSel"),oaryA.str_bank_id);
        	SelectDom.setSelect($("#endBankSel"),oaryA.end_bank_id);
        	SelectDom.setSelect($("#mdlCateSel"),oaryA.mdl_cate);
        }
      } 
  });

  //页面高度变化时，自动调整Grid大小
  var resetJqgrid = function(){
      $(window).unbind("onresize"); 
      $("#pathListGrd").setGridWidth($("#pathListDiv").width()*0.95); 
      $("#pathListGrd").setGridHeight($("pathListDiv").height()*0.80); 
      $(window).bind("onresize", this);  
  };
  function initMdlCate(){
  	var outObj = baseFnc.sendXplstData("MDCT");
  	SelectDom.initWithSpace($("#mdlCateSel"));
	SelectDom.addSelectArr($("#mdlCateSel"),outObj.oary,"data_ext","data_desc");
  }
  function initFnc(){
    $("input").attr({'disabled':true});
    $("select").attr({'disabled':true});
    $("input").val("");
    $("select").empty();
    initMdlCate();
  }
  
  

  function f1QueryFnc(){

    function diaLogQueryFnc(){
      var iaryA = {};
      if($("#queryPathDialog_pathCateTxt").val()!=""){
        iaryA.path_cate = $("#queryPathDialog_pathCateTxt").val();
      }
      if($("#queryPathDialog_pathIDTxt").val()!=""){
        iaryA.path_id = $("#queryPathDialog_pathIDTxt").val();
      }
      if($("#queryPathDialog_pathVerTxt").val()!=""){
        iaryA.path_ver = $("#queryPathDialog_pathVerTxt").val();
      }
      var inTrxObj ={
         trx_id     : "XPBISPTH" ,
         action_flg : 'Q'        ,   
         iaryA      : [iaryA]    ,
         tbl_cnt_a  : 1
      };
      var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
      if(  outTrxObj.rtn_code == _NORMAL ) {
         setGridInfo(outTrxObj.oaryA,"#pathListGrd");
         $('#queryPathDialog').modal("hide");
      }
    }
    
    $('#queryPathDialog').modal({
        backdrop:true,
        keyboard:false,
        show:false
    });
    $('#queryPathDialog').unbind('shown.bs.modal');
    $("#queryPathDialog_queryBtn").unbind('click');

    $('#queryPathDialog').bind('shown.bs.modal');
    $('#queryPathDialog').modal("show");
    $("#queryPathDialog_queryBtn").bind('click',diaLogQueryFnc);
    $("#queryPathDialog input").attr({'disabled':false});
  }
  function f4DeleteFnc(){
    var selectID = $("#pathListGrd").jqGrid("getGridParam", "selrow" );
    if( selectID == null){
      showErrorDialog("003","请选择需要删除的工艺路线");
      return false;
    }
    var rowData  = $("#pathListGrd").jqGrid("getRowData",selectID);
    $("#f4_del_btn").showCallBackWarnningDialog({
          errMsg  : "是否删除工艺路线,请确认!!!!",
          callbackFn : function(data) {
            if(data.result==true){
              
              var iaryA ={};
              iaryA.path_id  = rowData.path_id;
              iaryA.path_ver = rowData.path_ver;
              var inTrxObj = {
                trx_id     : "XPBISPTH",
                action_flg :"D",
                iaryA      : [iaryA],
                tbl_cnt_a  : 1
              };
              var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
              if(  outTrxObj.rtn_code == _NORMAL ) {
                showSuccessDialog("删除工艺路线成功");
                $("#pathConditionForm select").empty();
                $("#pathConditionForm input").val("");
                $("#pathListGrd").jqGrid('delRowData', selectID);
              }
            }
          }
    });
    
  }
  function setSelectObjByToolCateFnc(selectObj,tool_cate){
    var selectTxt = $(selectObj).find("option:selected").text();
     $(selectObj).empty();
     var iary = {
        tool_cate : tool_cate   
     };
     var inTrxObj = {
         trx_id      : 'XPBISTOL' ,
         action_flg : 'Q'        ,
         iary        : [iary]
     };
     var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
     if(  outTrxObj.rtn_code == "0000000" ) {
          var tbl_cnt = comParseInt( outTrxObj.tbl_cnt);
          if( tbl_cnt == 1 ){
            //下面的tool_id要加双引号"tool-_id", oary.tool_id=oary["tool_id"]
            $(selectObj).append("<option value="+ outTrxObj.oary["tool_id"] +">"+ outTrxObj.oary["tool_id"] +"</option>");
          }else if(tbl_cnt>1){
            for(var i=0;i<tbl_cnt;i++){
              $(selectObj).append("<option value="+ outTrxObj.oary[i]["tool_id"] +">"+ outTrxObj.oary[i]["tool_id"] +"</option>");
            }
            queryObj.select2({
    	    	theme : "bootstrap"
    	    });
          }
     }
    $(selectObj).val(selectTxt);     
  }
  function setBankFnc(){
    var iary,
      inTrxObj,
      outTrxObj,
      tool_cate,
      tbl_cnt,
      oary;
    var oldStartBank = $("#startBankSel").find("option:selected").text();
    var oldEndBank   = $("#endBankSel").find("option:selected").text();
    iary = [{
       unit_typ  : "BANK"
       // tool_cate : "STBK"
    }];
    inTrxObj = {
      trx_id      : "XPBISTOL",
      action_flg  : "Q"       ,
      iary        : iary      ,
      tbl_cnt     : 1
    };
    outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if( outTrxObj.rtn_code=="0000000"){
        tbl_cnt = outTrxObj.tbl_cnt;
          for(var i=0;i<tbl_cnt;i++){
            oary = tbl_cnt > 1 ?  outTrxObj.oary[i]: outTrxObj.oary;
            tool_cate = oary.tool_cate;
            if(tool_cate=="STBK"){
              $("#startBankSel").append("<option value="+oary.tool_id+">" +oary.tool_id +"</option>"); 
              $("#startBankSel").select2({
      	    	theme : "bootstrap"
      	    });
            }else if(tool_cate=="ENBK"){
              $("#endBankSel").append("<option value="+oary.tool_id+">" +oary.tool_id +"</option>"); 
              $("#endBankSel").select2({
      	    	theme : "bootstrap"
      	    });
            }
           
       }
    }
  }
  var baseFnc = {
		sendXplstData : function(dataCate) {
			var inObj = {
				trx_id : "XPLSTDAT",
				action_flg : "Q",
				iary : [{
					data_cate : dataCate
				}]
			};
			outObj = comTrxSubSendPostJson(inObj);
			return outObj.rtn_code === "0000000" ? outObj : false;
		}
	};
		
  function f6AddFnc(){
    var outObj;
    $("#pathConditionForm input").attr({'disabled':false});
    $("#pathConditionForm select").attr({'disabled':false});
    $("#pathConditionForm input").val("");
    $("#pathConditionForm select").empty();
    setBankFnc();
    addValueByDataCateFnc("#pathCateSel","RCAT","data_ext");
    outObj = baseFnc.sendXplstData("MDCT");
	$("#mdlCateSel").empty();
	SelectDom.addSelectArr($("#mdlCateSel"),outObj.oary,"data_ext","data_desc");
    $("#pathItemListGrd").jqGrid("clearGridData");
    $("#f8_regist_btn").data("regist_flg","A");
  }
  function savePathInfoFnc(){
	    if($("#pathIDTxt").val()==""){
	      showErrorDialog("003","请输入工艺路线");
	      $("#pathIDTxt").focus();
	      return false;
	    }
	    if($("#pathVerTxt").val()==""){
	      showErrorDialog("003","请输入工艺路线版本");
	      $("#pathVerTxt").focus();
	      return false;
	    }
	    var mdlCate = $("#mdlCateSel").val();
	    if(!mdlCate){
	    	showErrorDialog("","请选择工艺属性");
	    	return false;
	    }
	    var iaryA     = {
	      path_id    : $("#pathIDTxt").val(),
	      path_ver   : $("#pathVerTxt").val(),
	      path_dsc   : $("#pathDscTxt").val(),
	      path_cate  : $("#pathCateSel").find("option:selected").text(),
	      str_bank_id: $("#startBankSel").find("option:selected").text(),
	      end_bank_id: $("#endBankSel").find("option:selected").text(),
	      mdl_cate   : mdlCate
	    };

	    var inTrxObj = {
	       trx_id      : 'XPBISPTH' ,
	       action_flg  : 'A'        ,
	       iaryA       : [iaryA]      ,
	       tbl_cnt_a   : 1
	    };
	    var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
	    if(  outTrxObj.rtn_code == "0000000" ) {
	        var newRowID = getGridNewRowID("#pathListGrd");
	        $("#pathListGrd").jqGrid("addRowData",newRowID,iaryA);
	        $("#pathConditionForm input").attr({'disabled':true});
	        $("#pathConditionForm select").attr({'disabled':true});
	        return true;
	    }
  }
  function savePathItemFnc(){
    var rowIDs = $("#pathItemListGrd").jqGrid("getDataIDs");
    if(rowIDs.length<=0){
      return false;
    }
    var rowCnt = rowIDs.length;
    var iaryBList = [];
    var iaryA = {};
    for(var i=0;i<rowIDs.length;i++){
      var pvRowData  = null; 
      var crRowData  = null; 
      var nxRowData  = null;

      var crRowData =$("#pathItemListGrd").jqGrid("getRowData",rowIDs[i]);
      if(i<rowCnt-1){
          rowData2 = $("#pathItemListGrd").jqGrid("getRowData",rowIDs[i+1]);  
      }
      var iaryB = crRowData;
      
      iaryB.path_id_fk  = $("#pathIDTxt").val();
      iaryB.path_ver_fk = $("#pathVerTxt").val();
      if(i==0){
        nxRowData       = $("#pathItemListGrd").jqGrid("getRowData",rowIDs[i+1]);
        iaryB.pv_ope_no = "FRST" ;
        iaryB.nx_ope_no = nxRowData.cr_ope_no ;
        iaryA.first_ope_no = crRowData.cr_ope_no;
      }else if(i==rowCnt.length-1){
        crRowData       = $("#pathItemListGrd").jqGrid("getRowData",rowIDs[i-1]);
        iaryB.pv_ope_no = pvRowData.cr_ope_no ;
        iaryB.nx_ope_no = "LAST" ;
      }else{
        nxRowData = $("#pathItemListGrd").jqGrid("getRowData",rowIDs[i+1]);
        crRowData = $("#pathItemListGrd").jqGrid("getRowData",rowIDs[i-1]);
        iaryB.pv_ope_no = crRowData.cr_ope_no ;
        iaryB.nx_ope_no = nxRowData.cr_ope_no ;
      }
      iaryBList.push(iaryB);
    }
    var inTrxObj = {
         trx_id      : 'XPBISPTH' ,
         action_flg  : 'N'        ,
         iaryB       : iaryBList  ,
         tbl_cnt_b   : rowCnt     ,
         iaryA       : [iaryA]      ,
         tbl_cnt_a   : 1
    };
    var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if(  outTrxObj.rtn_code == "0000000" ) {
        return true;
    }
  }
  function f8RegistFnc(){
    var registFlg = $("#f8_regist_btn").data("regist_flg");
    isPathChange = ( $("#pathIDTxt").attr("disabled") !== "disabled" ) ;
    if(isPathChange){
    	var isSuccess = savePathInfoFnc() && savePathItemFnc();
	    if( isSuccess ==true){
	        showSuccessDialog("新增工艺成功");  
	    }
    }else{
       var isSuccess = savePathItemFnc();
       if( isSuccess ==true){
           showSuccessDialog("新增工艺成功");  
       }
    }
  }
  function f10ClearFnc(){
    $("input").val("");
    $("select").empty();
    $("#pathListGrd").jqGrid("clearGridData");
  }

  $("#f1_query_btn").click(f1QueryFnc);

  $("#f6_add_btn").click(f6AddFnc);
  $("#f8_regist_btn").click(f8RegistFnc);
  $("#f4_del_btn").click(f4DeleteFnc);
  $("#f10_clear_btn").click(f10ClearFnc);
  initFnc();  
})